<template>
  <div class="category _page _container">
    <UiBreadcrumbs
      :items="breadcrumbs"
      class="_breadcrumbs-info"
    />

    <InfoMain
      v-if="categoryInfoResult && isFirstPage"
      :key="`info-${categoryInfo?.header}`"
      :card="categoryInfoResult"
      type="category"
      class="category__info"
    />

    <UiExpandRow
      v-if="relatedCategories && relatedCategories.length && relatedCategories.length > 0"
      :items="relatedCategories"
      :pre-text="`${$t('related_categories')}:`"
      class="category__related-categories"
    />

    <LazySectionToolbar
      class="category__options"
      hydrate-on-idle
    />

    <GridVideos
      v-if="data && data.items && data.items?.length > 0"
      id="anchor"
      :items="data.items"
      priority
      :class="{'_loading': status === 'pending'}"
    >
      <template #grid-end>
        <LazyAdvNativeBottom
          v-if="featureFlags.AdsNativeEnabled"
          hydrate-on-visible
        />
      </template>
      <template #default>
        <UiExpandRow
          v-if="isChipsShow && relatedSearch && relatedSearch.length && relatedSearch.length > 0 && statusRelated !== 'pending'"
          :items="relatedSearch"
          :pre-text="`${$t('related_searches')}: `"
          class="category__related-searches"
        />
        <div
          v-else-if="statusRelated === 'pending'"
          class="category__related-loading _loading"
        />
        <LazySectionSwiperCards
          hydrate-on-visible
          v-if="modelsByCategory && modelsByCategory.items && modelsByCategory.items.length > 0"
          :items="modelsRoundCards"
          :title="$t('category_top_models_title', {name: title})"
          class="category__models"
          placeholder-avatar="/img/model-placeholder.webp"
        />
      </template>
    </GridVideos>
    <div
      v-else-if="status === 'pending'"
      class="category__loading _loading"
    />
    <UiEmptyState v-else/>

    <UiPagination
      v-if="data"
      arrow-icon
      :key="`pagination-${data.allPages}`"
      :total="data.allPages"
      class="category__pagination _pagination"
    />

    <LazyUiFullDescr
      v-if="isFirstPage && categoryInfo?.fullDescription"
      :text="categoryInfo.fullDescription"
      hydrate-on-visible
    />
  </div>
</template>

<script setup lang="ts">
import { CategoriesApiService } from '../../services/api/categories.service';
import { VideosApiService } from '../../services/api/videos.service';
import { ModelsApiService } from '../../services/api/models.service';
import { convertModelToRoundCard } from '../../runtime';
import type { ICardInfo } from '../../types';
import { computed, unref } from 'vue';

const featureFlags = useRuntimeConfig().public.featureFlags;

const { t } = useI18n();

const route = useRoute();
const disallowedSlugs = ['18', '19'];

const slug = useSlug();

const [
  { data: categoryInfo },
  { data, status },
  { data: relatedData, status: statusRelated },
  { data: modelsByCategory },
] = await Promise.all([
  useFetchCategoriesByName(CategoriesApiService.getCategoriesByName),
  useFetchVideosByCategories(VideosApiService.getListByNicheAndCategory),
  useFetchCategoriesRelated(CategoriesApiService.getRelatedCategories),
  useFetchModelsByCategory(ModelsApiService.getListByCategory, 100),
]);

const isChipsShow = computed(() => !disallowedSlugs.some((item) => slug.value.includes(item)));

const relatedSearchRaw = computed(() => {
  if (!isChipsShow.value) return null;
  return relatedData.value || null;
});

const modelsRoundCards = computed(() =>
    modelsByCategory.value?.items.map(convertModelToRoundCard) || []
);

const categoryInfoResult = computed(() => ({
  title: categoryInfo.value?.header,
  description: categoryInfo.value?.description,
  videosCount: categoryInfo.value?.videosCount,
  guid: categoryInfo.value?.guid,
  miniCardTitle: categoryInfo.value?.title,
} as ICardInfo));

const relatedSearch = computed(() => relatedSearchRaw.value?.items?.map(item => ({
  title: item.query,
  value: item.query,
  prefix: 'search',
})) || []);

const relatedCategories = computed(() => categoryInfo.value?.related);

const title = computed(() => categoryInfo.value?.title || '');
const metaTitle = computed(() => categoryInfo.value?.metaTitle || '');
const brandName = computed(() => useAppConfig().brandName);
const pageNumber = computed(() => route.query?.[ 'page' ] ? Number(route.query[ 'page' ]) : 1);
const pageText = computed(() => unref(pageNumber) === 1 ? '' : ` ${t('page')} ${unref(pageNumber)}`);

watchEffect(() => {
  const categoryTitle = `${metaTitle.value}${pageText.value} | ${brandName.value}`;
  const categoryDescription = `${categoryInfo.value?.metaDescription || ''}${pageText.value}`;

  useHead({
    title: categoryTitle,
    meta: [
      { name: 'description', content: categoryDescription },
      { property: 'og:title', content: categoryTitle },
      { property: 'og:description', content: categoryDescription },
      { name: 'twitter:title', content: categoryTitle },
      { name: 'twitter:description', content: categoryDescription },
    ],
  });

  if (
      status.value === 'success' &&
      (!data.value || !categoryInfo.value)
  ) {
    throw createError({ statusCode: 404, statusMessage: 'Not Found' });
  }
});

const isFirstPage = computed(() => !route.query[ 'page' ] || route.query[ 'page' ] === '1');

const breadcrumbs = [
  {
    name: `${t('navigation.main')}`,
    to: '/',
  },
  {
    name: `${t('navigation.categories')}`,
    to: '/categories',
  },
  {
    name: title.value,
  },
];
</script>

<style lang="scss">
.category__options {
  margin-bottom: 24px;
}

.category__options:has(.ui-expand-row) {
  margin-bottom: 16px;
}

.category__loading {
  height: 100%;
  min-height: 30vh;
}

.category__models {
  margin-top: 40px;
}

.category__info {
  margin-bottom: 24px;
}

.category__related-loading {
  --size: 20px;

  height: 24px;

  @include from-br(sm) {
    height: 32px;
  }
}

.category__models,
.category__related-searches {
  grid-column: 1/-1;
  grid-row: 2;
  margin-block: 8px;
}

.category__related-searches + .category__models {
  grid-row: 3;
}

.category__top {
  display: grid;
  row-gap: 8px;
  margin-top: auto;

  @include from-br(sm) {
    row-gap: 16px;
  }
}

.category__related-categories {
  margin-bottom: 24px;
}

.category__pagination {
  margin-top: 32px;
}
</style>
